<template>
  <div class="news-container">
    <el-container>
      <el-header class="news-header">
        <div class="header-left">
          <h2>消息管理</h2>
          <el-input
            v-model="searchQuery"
            placeholder="搜索消息..."
            class="search-input"
            clearable
            @clear="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <el-button type="primary" @click="handleAddNews" round icon="Plus">
          发布消息
        </el-button>
      </el-header>
      <el-main>
        <div class="news-list" v-loading="loading">
          <div v-if="newsList.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无消息" />
          </div>
          <div v-for="item in newsList" :key="item.id" class="news-item">
            <div class="news-item-header">
              <div class="news-item-title">
                <el-icon><Bell /></el-icon>
                <h3>{{ item.title }}</h3>
                <el-tag size="small" type="info" class="news-time">{{ item.created_at }}</el-tag>
              </div>
              <div class="news-actions" v-if="item.user_id === currentUserId">
                <el-button type="primary" size="small" @click="handleEditNews(item)" icon="Edit" round>
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="handleDeleteNews(item)" icon="Delete" round>
                  删除
                </el-button>
              </div>
            </div>
            <div class="news-item-content">
              <p>{{ item.content }}</p>
              <div class="news-meta">
                <span class="publisher">
                  <el-icon><User /></el-icon>
                  {{ item.username }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 发布/编辑消息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑消息' : '发布消息'"
      width="50%"
      class="news-dialog"
    >
      <el-form :model="newsForm" :rules="rules" ref="newsFormRef">
        <el-form-item label="标题" prop="title">
          <el-input v-model="newsForm.title" placeholder="请输入消息标题" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="newsForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入消息内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitNews" round>
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Plus, Delete, Search, Bell, User } from '@element-plus/icons-vue'
import { newsApi } from '../api'
import { useUserStore } from '../stores/user'

const userStore = useUserStore()
const currentUserId = computed(() => userStore.userId)
const searchQuery = ref('')
const loading = ref(false)

// 消息列表数据
const newsList = ref([])

// 获取消息列表
const fetchNews = async () => {
  loading.value = true
  try {
    const params = searchQuery.value ? { q: searchQuery.value } : {}
    const data = await newsApi.getNews(params)
    newsList.value = data
  } catch (error) {
    if (error.response?.status !== 401) {
      ElMessage.error('获取消息列表失败')
    }
  } finally {
    loading.value = false
  }
}

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const newsFormRef = ref(null)
const newsForm = ref({
  title: '',
  content: ''
})

const rules = {
  title: [
    { required: true, message: '请输入消息标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 处理搜索
const handleSearch = () => {
  fetchNews()
}

// 处理发布消息
const handleAddNews = () => {
  isEdit.value = false
  newsForm.value = {
    title: '',
    content: ''
  }
  dialogVisible.value = true
}

// 处理编辑消息
const handleEditNews = (news) => {
  isEdit.value = true
  newsForm.value = {
    id: news.id,
    title: news.title,
    content: news.content
  }
  dialogVisible.value = true
}

// 处理删除消息
const handleDeleteNews = async (news) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await newsApi.deleteNews(news.id)
    ElMessage.success('删除成功')
    fetchNews()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理提交消息
const handleSubmitNews = async () => {
  if (!newsFormRef.value) return

  await newsFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await newsApi.updateNews(newsForm.value.id, newsForm.value)
          ElMessage.success('编辑成功')
        } else {
          await newsApi.createNews(newsForm.value)
          ElMessage.success('发布成功')
        }
        dialogVisible.value = false
        fetchNews()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    }
  })
}

onMounted(() => {
  fetchNews()
})
</script>

<style scoped>
.news-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e3f0ff 100%);
}

.news-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: transparent;
  border-bottom: none;
  padding: 0 20px 24px 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-input {
  width: 300px;
}

.news-list {
  max-width: 800px;
  margin: 0 auto;
}

.news-item {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
}

.news-item:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  transform: translateY(-2px);
}

.news-item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.news-item-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.news-item-title h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.news-time {
  margin-left: 8px;
}

.news-item-content {
  color: #606266;
  line-height: 1.6;
}

.news-meta {
  margin-top: 12px;
  display: flex;
  align-items: center;
  gap: 16px;
  color: #909399;
  font-size: 14px;
}

.publisher {
  display: flex;
  align-items: center;
  gap: 4px;
}

.news-actions {
  display: flex;
  gap: 8px;
}

.news-dialog .el-dialog__body {
  padding: 32px 24px 12px 24px;
}

.news-dialog .el-dialog__footer {
  padding-bottom: 24px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

@media (max-width: 768px) {
  .news-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-left {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .news-item-header {
    flex-direction: column;
    gap: 12px;
  }

  .news-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 